import { readMultipartFormData, sendError } from "h3";
import { v4 as uuidv4 } from "uuid";
import fs from "fs";
import path from "path";

export default defineEventHandler(async (event) => {
  const images = await readMultipartFormData(event);
  if (!images) {
    return sendError(
      event,
      createError({ statusCode: 400, statusMessage: "未找到图片文件" })
    );
  }

  // 验证文件类型和大小的函数
  const validateImage = (image: any) => {
    const allowedMimeTypes = [
      "image/jpeg",
      "image/png",
      "image/gif",
      "image/webp",
    ];
    if (!allowedMimeTypes.includes(image.type || "")) {
      return { valid: false, message: `不支持的文件类型: ${image.filename}` };
    }

    const maxSize = 5 * 1024 * 1024; // 5MB
    if (image.data.length > maxSize) {
      return {
        valid: false,
        message: `文件大小超过限制: ${image.filename} (最大 5MB)`,
      };
    }

    return { valid: true };
  };

  // 验证所有图片
  for (const image of images) {
    const validation = validateImage(image);
    if (!validation.valid) {
      return sendError(
        event,
        createError({
          statusCode: 400,
          statusMessage: validation.message,
        })
      );
    }
  }

  // 创建上传目录（如果不存在）
  const uploadDir = path.join(process.cwd(), "public", "uploads");
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }

  try {
    // 保存所有图片并收集结果
    const results = [];
    for (const image of images) {
      let ext = "png";
      let filename_pre = `${Date.now()}_${uuidv4()}`;

      if (image.filename) {
        let fileNameList = image.filename?.split(".") || [];
        if (fileNameList.length > 0) {
          filename_pre = fileNameList[0] + "_" + filename_pre;
        }

        ext = fileNameList.pop() || "png";
      }

      const filename = `${filename_pre}.${ext}`;
      const filePath = path.join(uploadDir, filename);

      fs.writeFileSync(filePath, image.data);

      results.push({
        url: `/uploads/${filename}`,
        filename,
        size: image.data.length,
        originalName: image.filename,
      });
    }

    // 返回所有文件信息
    return {
      success: true,
      count: results.length,
      data: results,
    };
  } catch (error) {
    return sendError(
      event,
      createError({ statusCode: 500, statusMessage: "文件保存失败" })
    );
  }
});
